/**
 * 骗子酒馆-摸鱼派版本
 * @author: mitu2
 * @param options
 */
export function init(options = {}) {
    const currentUser = (window.Label || {}).currentUser || window.location.hostname + "_Player_" + (Math.floor(Math.random() * 10000))

    const baseLT = {
        player: currentUser,
        baseUrl: "https://game.metoo.ink",
        globalName: "LT",
        op: {},
    }
    const LT = Object.assign({}, baseLT, options, { v: "V.1.0" })

    if (window[LT.globalName] && window[LT.globalName].v === LT.v) {
        if (LT.uuid) {
            window[LT.globalName].play(LT.uuid).then()
        }
        return
    }
    const LOG = (msg, level = "#42c02e") => {
        console.log(
            `%c[LiarTavern]%c${ msg }`,
            'padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #606060; font-weight: bold;',
            `padding: 2px 1px; border-radius: 0 3px 3px 0; color: #fff; background: ${ level };`,
        )
    }
    const LOG_ERR = (msg) => LOG(msg, "#fb415e")
    const doApi = (path, params) => {
        params = params ? `&${ params }` : ""
        return fetch(`${ LT.baseUrl }/${ path }?player=${ LT.player }${ params }`)
            .then(resp => new Promise((resolve, reject) => {
                if (resp.status !== 200) reject(resp)
                resolve(resp)
            })
                .catch(err => {
                    err.json().then(json => {
                        LOG_ERR(json.message)
                    })
                    throw err
                }))
    }
    const APIS = {
        play: (uuid) => uuid ? doApi(`api/liar-tavern-game/${ uuid }/play`) : doApi(`api/liar-tavern-game/play`),
        watch: (uuid, version) => doApi(`api/liar-tavern-game/${ uuid }/watch`, `version=${ version }`),
        cards: (uuid, useCards) => doApi(`api/liar-tavern-game/${ uuid }/cards`, `use=${ useCards }`),
        bang: (uuid) => doApi(`api/liar-tavern-game/${ uuid }/bang`)
    }
    const PRIVATE = {
        watchInterval: -1,
        waitPlayer: '',
        NONE: () => {
        },
    }
    const clearGame = () => {
        if (PRIVATE.watchInterval || PRIVATE.watchInterval > 0) {
            clearInterval(PRIVATE.watchInterval)
        }
    }
    LT.play = async function (roomId) {
        const playResp = await APIS.play(roomId)
        console.clear()
        const {
            creator, uuid
        } = await playResp.json()
        let ots = ''
        if (LT.baseUrl !== baseLT.baseUrl) {
            ots = `, baseUrl: '${ LT.baseUrl }'`
        }
        if (creator === LT.player) {
            LOG(`已创建一个酒馆, 需满足4人开始游戏, 邀请方式对方控制台输入> import("${ LT.baseUrl }/liar-tavern-game.fishpi.js").then(({init}) => init({uuid: '${ uuid }'${ ots }}))`)
        } else {
            LOG(`已加入${ creator }的酒馆, 需满足4人开始游戏, 邀请方式对方控制台输入> import("${ LT.baseUrl }/liar-tavern-game.fishpi.js").then(({init}) => init({uuid: '${ uuid }'${ ots }}))`)
        }
        clearGame()
        let version = 0
        PRIVATE.uuid = uuid
        PRIVATE.watchInterval = setInterval(async () => {
            const watchResp = await APIS.watch(PRIVATE.uuid, version)
            const {
                events, lastVersion, playerDataList
            } = await watchResp.json()
            PRIVATE.playerDataList = playerDataList
            const printCardsButton = () => {
                const myself = PRIVATE.playerDataList.findLast(it => it.name === LT.player)
                const select = []
                let rest = false
                let op = {
                    get "质疑"() {
                        return LT.bang()
                    },
                    get "重置选择"() {
                        printCardsButton()
                        rest = true
                    },
                    get "出牌"() {
                        return !rest && LT.cards(...select)
                    }
                }
                let _record = myself.items || []
                for (let ele of _record) {
                    Object.defineProperty(op, Symbol(ele), {
                        get() {
                            select.push({
                                key: ele,
                                size: 1
                            })
                            return "已选择"
                        }
                    })
                }
                console.log("➡️ 操作按钮: ", Object.create(op), `本轮关键牌是: ${ PRIVATE.key }`)
            }
            for (let event of events) {
                const { type, player, record } = event
                switch (type) {
                    case "PLAYER_JOIN":
                        if (player === LT.player) {
                            console.log(`[+] 👴 ${ player }(我) 加入了酒馆`)
                        } else {
                            console.log(`[+] ${ player } 加入了酒馆`)
                        }
                        break
                    case "PLAYER_LEAVE":
                        console.log(`[-] ${ player } 退出了酒馆`)
                        break
                    case "GAME_START":
                        LOG_ERR(`游戏开始 规则如下📕 ?是对方的牌 K,Q,J,A分别有6张, S是万能牌仅有2张 根据每轮关键牌来伪装`)
                        break
                    case "GAME_END":
                        clearGame()
                        printBaseButton()
                        LOG_ERR(`游戏结束, 胜利者是: ${ record }`)
                        break
                    case "PLAYER_PLAY_CARDS":
                        if (player === LT.player) {
                            LOG(`您打出了 [ ${ record } ]`)
                        } else {
                            LOG(`${ player } 打出了 [ ${ record } ]`)
                        }
                        break
                    case "PLAYER_SHOOT":
                        LOG(`${ player } 对自己的大脑门开了一枪 (${ record }/6)`)
                        break
                    case "PLAYER_DEATH":
                        LOG_ERR(`倒霉催${ player }盖了帽了`)
                        break
                    case "PLAYER_BANG":
                        if (player === LT.player) {
                            LOG(`你对${ PRIVATE.preWaitPlayer }发出灵魂质疑`)
                        } else {
                            LOG(`${ player }觉得${ PRIVATE.preWaitPlayer }有诈`)
                        }
                        LOG(`揭秘${ record.player }出的牌是[ ${ record.useItems } ]`)
                        break
                    case "WAIT_PLAYER_OPERATE":
                        PRIVATE.preWaitPlayer = PRIVATE.waitPlayer
                        PRIVATE.waitPlayer = player
                        if (player === LT.player) {
                            LOG(`轮到您操作了, 下面将打印操作按钮`)
                            printCardsButton()
                        } else {
                            LOG(`轮到了${ player }操作`)
                        }
                        break
                    case "REFRESH_ITEM":
                        const { key } = record
                        PRIVATE.key = key
                        LT.show()
                        break
                }
            }
            version = lastVersion
        }, 2000)
    }

    LT.cards = function (...useCards) {
        const uks = useCards.flatMap(card => Array(card.size).fill(card.key))
        APIS.cards(PRIVATE.uuid, uks).then(PRIVATE.NONE)
    }

    LT.bang = function () {
        APIS.bang(PRIVATE.uuid).then(PRIVATE.NONE)
    }

    LT.show = function () {
        if (!PRIVATE.playerDataList) return
        let pds = PRIVATE.playerDataList || []
        pds = pds.map(pd => {
            const { name, status, items, shootNumber } = pd
            if (status === 'ALIVE') {
                return `  - 🧍‍♂️${ name } [💗] [🔫(${ shootNumber }/6)]: [ ${ items.join(', ') } ]`
            } else {
                return `  - 🧍‍♂️${ name } [☠️] [🔫(${ shootNumber }/6)]: [ ${ items.join(', ') } ]`
            }
        })
        console.log(`🎮 当前信息: 关键牌( ${ PRIVATE.key } ) \n${ pds.join("\n") }`)
    }
    LOG(`${ LT.player }. 骗子酒馆控制台版本初始化完成, 项目地址: https://gitcode.com/mitu2/fish-game 欢迎提出问题`)
    const printBaseButton = () => {
        console.log(`➡️ 操作按钮: `, Object.create({
            get "加入游戏"() {
                const rid = prompt("请输入房间号")
                return rid && LT.play(rid)
            },
            get "创建游戏"() {
                return LT.play()
            },
            get "刷新操作按钮"() {
                printBaseButton()
                return "请看下面"
            },
        }))
    }
    if (LT.uuid) {
        LT.play(LT.uuid).then()
    } else {
        printBaseButton()
    }
    window[LT.globalName] = LT
}